import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import 'package:kudos/core/utils/kudo_url.dart';
import 'package:kudos/core/widget/loading_widget.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import '../../state/person/persona_session_controller.dart';
import '../../utils/kudo_helper.dart';
import '../../router/app_navigation_manager.dart';

class AccountCreationScreen extends StatefulWidget {
  const AccountCreationScreen({super.key});

  @override
  State<AccountCreationScreen> createState() => _AccountCreationScreenState();
}

class _AccountCreationScreenState extends State<AccountCreationScreen> {
  final TextEditingController _accountInputController = TextEditingController();
  final TextEditingController _passwordInputController =
      TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final GlobalKey<FormState> _formValidationKey = GlobalKey<FormState>();

  bool _isProcessingRegistration = false;
  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  String? _accountValidationError;
  String? _passwordValidationError;
  String? _confirmPasswordValidationError;

  @override
  void dispose() {
    _accountInputController.dispose();
    _passwordInputController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: [
          _buildNavigationHeaderSection(),

          Expanded(
            child: [
              _buildBrandingSection().paddingTop(10.h),
              SizedBox(height: 55.h),

              _buildRegistrationFormSection(),
            ].toColumn(mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          ),
        ].toColumn().safeArea(bottom: false),
      ),
    );
  }

  Widget _buildNavigationHeaderSection() {
    return [
          Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black,
            size: 20.w,
          ).inkWell(onTap: () => Navigator.of(context).pop()),
        ]
        .toRow(mainAxisAlignment: MainAxisAlignment.start)
        .paddingHorizontal(16.w)
        .paddingTop(20.h);
  }

  Widget _buildBrandingSection() {
    return [
      Container(
        width: 90.w,
        height: 90.w,
        decoration: BoxDecoration(
          image: DecorationImage(image: AssetImage('assets/images/logo.png')),
        ),
      ),

      Text('Kudos')
          .fontSize(28.sp)
          .fontWeight(FontWeight.w900)
          .fontFamily(GoogleFonts.montserrat().fontFamily)
          .textColor(KudoColors.black)
          .textShadow(
            color: KudoColors.yellow,
            blurRadius: 0,
            offset: const Offset(0, 4),
          )
          .paddingTop(10.h),
    ].toColumn();
  }

  Widget _buildRegistrationFormSection() {
    return Flexible(
      child:
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              color: const Color(0xFFFFF9C8),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.r),
                topRight: Radius.circular(30.r),
              ),
            ),
            child: SingleChildScrollView(
              child: Form(
                key: _formValidationKey,
                child: [
                  _buildAccountInputSection(),

                  _buildPasswordInputSection(),

                  _buildConfirmPasswordInputSection(),

                  SizedBox(height: 26.h),

                  _buildRegisterButtonSection(),

                  SizedBox(height: 10.h),

                  _buildLoginLinkSection(),

                  _buildTermsOfServiceSection(),
                ].toColumn().paddingHorizontal(16.w).paddingVertical(24.h),
              ),
            ),
          ).alignBottom(),
    );
  }

  Widget _buildAccountInputSection() {
    return [
      Text(
        'Account',
      ).fontSize(16.sp).fontWeight(FontWeight.w600).textColor(Colors.black87),

      SizedBox(height: 8.h),

      Container(
        height: 51.h,
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                _accountValidationError != null
                    ? Colors.red
                    : Colors.transparent,
            width: 2,
          ),
        ),
        child: TextField(
          controller: _accountInputController,
          decoration: InputDecoration(
            hintText: 'Nome Completo',
            hintStyle: TextStyle(color: Colors.black54, fontSize: 16.sp),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
          ),
          textAlignVertical: TextAlignVertical.center,
          style: TextStyle(
            color: Colors.black87,
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ).configWidget(borderRadius: 14.r),

      if (_accountValidationError != null)
        Text(
          _accountValidationError!,
        ).fontSize(12.sp).textColor(Colors.red).paddingTop(4.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildPasswordInputSection() {
    return [
      Text(
        'Password',
      ).fontSize(16.sp).fontWeight(FontWeight.w600).textColor(Colors.black87),

      SizedBox(height: 8.h),

      Container(
        height: 51.h,
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                _passwordValidationError != null
                    ? Colors.red
                    : Colors.transparent,
            width: 2,
          ),
        ),
        child: TextField(
          controller: _passwordInputController,
          obscureText: !_isPasswordVisible,
          decoration: InputDecoration(
            hintText: 'Password',
            hintStyle: TextStyle(color: Colors.black54, fontSize: 16.sp),
            suffixIcon: IconButton(
              icon: Icon(
                _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
                color: Colors.black54,
                size: 20.w,
              ),
              onPressed: () {
                setState(() {
                  _isPasswordVisible = !_isPasswordVisible;
                });
              },
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
          ),
          textAlignVertical: TextAlignVertical.center,
          style: TextStyle(
            color: Colors.black87,
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ).configWidget(borderRadius: 14.r),

      if (_passwordValidationError != null)
        Text(
          _passwordValidationError!,
        ).fontSize(12.sp).textColor(Colors.red).paddingTop(4.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start).paddingTop(16.h);
  }

  Widget _buildConfirmPasswordInputSection() {
    return [
      Text(
        'Password Again',
      ).fontSize(16.sp).fontWeight(FontWeight.w600).textColor(Colors.black87),
      SizedBox(height: 8.h),
      Container(
        height: 51.h,
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                _confirmPasswordValidationError != null
                    ? Colors.red
                    : Colors.transparent,
            width: 2,
          ),
        ),
        child: TextField(
          controller: _confirmPasswordController,
          obscureText: !_isConfirmPasswordVisible,
          decoration: InputDecoration(
            hintText: 'Password Again',
            hintStyle: TextStyle(color: Colors.black54, fontSize: 16.sp),
            suffixIcon: IconButton(
              icon: Icon(
                _isConfirmPasswordVisible
                    ? Icons.visibility_off
                    : Icons.visibility,
                color: Colors.black54,
                size: 20.w,
              ),
              onPressed: () {
                setState(() {
                  _isConfirmPasswordVisible = !_isConfirmPasswordVisible;
                });
              },
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
          ),
          textAlignVertical: TextAlignVertical.center,
          style: TextStyle(
            color: Colors.black87,
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ).configWidget(borderRadius: 14.r),

      if (_confirmPasswordValidationError != null)
        Text(
          _confirmPasswordValidationError!,
        ).fontSize(12.sp).textColor(Colors.red).paddingTop(4.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start).paddingTop(16.h);
  }

  Widget _buildRegisterButtonSection() {
    return Container(
          width: double.infinity,
          height: 51.h,
          decoration: BoxDecoration(
            color: KudoColors.yellow,
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: Colors.black, width: 2),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child:
              _isProcessingRegistration
                  ? LoadingAnimationWidget.threeRotatingDots(
                    color: Colors.black,
                    size: 24.w,
                  ).center()
                  : Text('REGISTER')
                      .fontSize(18.sp)
                      .fontWeight(FontWeight.bold)
                      .textColor(Colors.black)
                      .center(),
        )
        .configWidget(borderRadius: 14.r)
        .inkWell(
          onTap: _isProcessingRegistration ? null : _executeRegistrationProcess,
        );
  }

  Widget _buildTermsOfServiceSection() {
    return [
      Text(
        'By continuing, you agree to our ',
      ).fontSize(10.sp).textColor(Colors.black54),
      Text(
        'Terms of Service',
        style: TextStyle(
          fontSize: 10.sp,
          fontWeight: FontWeight.w600,
          color: KudoColors.black,
          decoration: TextDecoration.underline,
        ),
      ).inkWell(onTap: _showTermsOfService),
      Text(' and ').fontSize(12.sp).textColor(Colors.black54),
      Text(
        'EULA',
        style: TextStyle(
          fontSize: 10.sp,
          fontWeight: FontWeight.w600,
          color: KudoColors.black,
          decoration: TextDecoration.underline,
        ),
      ).inkWell(onTap: _showEULA),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center).paddingTop(20.h);
  }

  void _executeRegistrationProcess() async {
    if (_accountValidationError != null ||
        _passwordValidationError != null ||
        _confirmPasswordValidationError != null) {
      KudoToast.showWarningToast(context, 'Please fix the errors above');
      return;
    }

    final account = _accountInputController.text.trim();
    final password = _passwordInputController.text.trim();

    if (account.isEmpty || password.isEmpty) {
      KudoToast.showWarningToast(context, 'Please fill in required fields');
      return;
    }

    setState(() {
      _isProcessingRegistration = true;
    });

    try {
      final success = PersonaSessionController.quickRegister(
        account,
        password,
        account,
      );

      LoadingWidget.showLoadingDialog(
        context,
        message: 'Registering...',
        color: KudoColors.green,
        animationType: LoadingAnimationType.threeRotatingDots,
      );

      await Future.delayed(const Duration(milliseconds: 2000));

      if (mounted) {
        setState(() {
          _isProcessingRegistration = false;
        });

        if (success) {
          KudoToast.showSuccessToast(context, 'Registration successful');
          GoRouter.of(context).pop();
        } else {
          KudoToast.showErrorToast(context, 'Account already exists');
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isProcessingRegistration = false;
        });
        KudoToast.showErrorToast(
          context,
          'Registration failed: ${e.toString()}',
        );
      }
    }
  }

  Widget _buildLoginLinkSection() {
    return [
      Text(
        'Already have an account? ',
      ).fontSize(14.sp).textColor(Colors.black54),
      Text('Sign In')
          .fontSize(14.sp)
          .fontWeight(FontWeight.w600)
          .textColor(const Color(0xFF00BCD4))
          .inkWell(onTap: _navigateToLogin),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center).paddingTop(16.h);
  }

  void _navigateToLogin() {
    AppNavigationManager.navigateToCredentialEntry(context);
  }

  void _showTermsOfService() {
    KudoOpen.openTerms();
  }

  void _showEULA() {
    KudoOpen.openEula();
  }
}
